package com.whmall.service.crm.module.supplierreview.impl;

import com.whmall.service.crm.module.supplierreview.SupplierReviewTagCategoryManager;
import com.whmall.service.crm.module.supplierreview.entity.SupplierReviewTagCategoryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 基于Redis的供应商评论标签分类管理器
 *
 * @author alex
 * @since 2021/1/18
 */
@Component
@RequiredArgsConstructor
public class RedisSupplierReviewTagCategoryManager implements SupplierReviewTagCategoryManager {
    private final static String REDIS_KEY = "$supplier_review_tag_category";
    private final RedisTemplate<String, SupplierReviewTagCategoryVO> redisTemplate;

    @Override
    public SupplierReviewTagCategoryVO findById(Integer categoryId) {
        SupplierReviewTagCategoryVO category = hashOperators().get(categoryId);
        if (null == category) {
            return null;
        }

        category.setId(categoryId);
        return category;
    }

    @Override
    public List<SupplierReviewTagCategoryVO> findByIds(List<Integer> categoryIds) {
        if (null == categoryIds || categoryIds.isEmpty()) {
            return Collections.emptyList();
        }

        AtomicInteger indexer = new AtomicInteger(0);
        return Objects.requireNonNull(hashOperators().multiGet(categoryIds))
                .stream()
                .peek(e -> {
                    int index = indexer.getAndIncrement();
                    if (null == e) {
                        return;
                    }
                    e.setId(categoryIds.get(index));
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    public List<SupplierReviewTagCategoryVO> findAll() {
        Map<Integer, SupplierReviewTagCategoryVO> entries = hashOperators().entries();
        if (null == entries) {
            return Collections.emptyList();
        }
        entries.forEach((k, v) -> v.setId(k));
        return new ArrayList<>(entries.values());
    }

    private BoundHashOperations<String, Integer, SupplierReviewTagCategoryVO> hashOperators() {
        return redisTemplate.boundHashOps(REDIS_KEY);
    }
}
